<template>
  <div>
    <video ref="video" autoplay width="100%"></video>
    <canvas ref="canvas" style="display: none;"></canvas>
    <a-button type="primary" size="small" @click="takePhoto" v-show="false">拍照</a-button>
    <img ref="photo" :src="photoSrc" alt="Photo" v-show="false" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from "vue";
import { apiUploadExamSnap } from "@/api/exam";

const props = defineProps({
  snapIntervalTime: {
    default: 1,
    type: Number
  },
  userExamId: {
    default: "",
    type: String
  }
});

const intervalId = ref();
const photoSrc = ref();
const video = ref();
const canvas = ref();

/**
 * 拍照
 */
function takePhoto() {
  const context = canvas.value.getContext("2d");
  const width = video.value.videoWidth;
  const height = video.value.videoHeight;
  canvas.value.width = width;
  canvas.value.height = height;
  context.drawImage(video.value, 0, 0, width, height);
  photoSrc.value = canvas.value.toDataURL("image/png");

  //上传抓拍图片到服务器
  apiUploadExamSnap({ userExamId: props.userExamId, base64Img: photoSrc.value });
}

async function startCamera() {
  try {
    video.value.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
  } catch (error) {
    console.error("Error accessing the camera:", error);
  }
}

onMounted(() => {
  startCamera();
  intervalId.value = setInterval(() => {
    takePhoto();//抓拍照片
  }, props.snapIntervalTime * 60 * 1000);
});

onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
});
</script>
